package com.example.filter;

import lombok.Data;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
//@Component
public class TimeGatewayFilterFactory extends AbstractGatewayFilterFactory<TimeGatewayFilterFactory.MyConfig> {

    public TimeGatewayFilterFactory(){
        super(MyConfig.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        List<String> list = Stream.of("show").collect(Collectors.toList());
        return list;
    }

    // 加工过滤器的方法
    @Override
    public GatewayFilter apply(MyConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                if (!config.show){
                    return chain.filter(exchange);
                }
                long begin = System.currentTimeMillis();
                return chain.filter(exchange).then(Mono.fromRunnable(()->{
                    // post 过滤器
                    long end = System.currentTimeMillis();
                    // 发送请求的客户端域名
                    String ip = exchange.getRequest().getRemoteAddress().getHostName();
                    // 请求的资源地址
                    String path = exchange.getRequest().getURI().getPath();

                    StringBuffer stringBuffer = new StringBuffer();
                    stringBuffer.append(ip).append("访问接口").append(path).append("耗时").append(end-begin).append("毫秒");
                    System.err.println(stringBuffer.toString());
                }));
            }
        };
    }


    @Data
    public static class MyConfig{
        private boolean show;
    }
}
